package com.example.springjpa.config;

import com.example.springjpa.pojo.User;
import com.example.springjpa.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 杰哥
 * @Title: CustomRealm
 * @ProjectName springjpa
 * @Description: TODO
 * @date 2019/8/159:17
 */
@Component
@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("****** 获取权限 *********");
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<User> byName = userService.findByName(username);
        Set<String> stringSet = new HashSet<>();
        User user = byName.get(0);
        String role = user.getRole();
        String[] split = role.split(":");
        for (String s : split) {
            stringSet.add(s);
        }
        //给那个用户一个 角色
        info.setRoles(stringSet);
        return info;
    }

    /**
     * 获取身份信息
     * shiro中 最终是通过realm 来获取用户的 角色和权限
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("****** 开始身份认证 *********");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String password = userService.findByName(token.getUsername()).get(0).getPassword();
        if (password == null){
            throw new AccountException("用户名不正确");
        }else if( !password.equals( new String((char[]) token.getCredentials()) )){
            throw  new AccountException("密码错误");
        }
        return  new SimpleAuthenticationInfo(token.getPrincipal(),password,getName());
    }
}
